<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Sensio\Bundle\HangmanBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use Sensio\Bundle\HangmanBundle\Form\PlayerType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;

class PlayerController extends Controller
{
    /**
     * @Route("/signup", name="signup")
     * @Template
     */
    public function signupAction(Request $request)
    {
        $form = $this->createForm(new PlayerType());
        $form->add("register","submit");
        
        $form->handleRequest($request);
        
        if($form->isValid())
        {
            $player = $form->getData();
            $factory = $this->get('security.encoder_factory');
            $encoder = $factory->getEncoder($player);
            
            $player->encodePassword($encoder);
            
            $em = $this->getDoctrine()->getManager();
            $em->persist($player);
            $em->flush();
            
            return $this->redirect($this->generateUrl('hangman_game'));
        }
        return array('form'=>$form->createView());
    }
    
    /**
     * 
     * @Route("/signin", name="signin")
     * @Template 
     */
    public function signinAction(Request $request)
    {
        $session = $request->getSession();
        if(($username = $session->get(SecurityContext::LAST_USERNAME))){
            $session->remove(SecurityContext::LAST_USERNAME);
        }
        if(($error = $session->get(SecurityContext::AUTHENTICATION_ERROR))){
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }
        
        return array('last_username'=>$username,'error'=>$error);
    }
    
    /**
     * @Cache(smaxage = 120)
     * @Template
     */
    public function playersAction($limit)
    {
        $em = $this->getDoctrine()->getManager();
        
        $repository = $em->getRepository('SensioHangmanBundle:Player');
        
        return array('players'=>$repository->getMostRecentPlayers($limit));
    }

}